/*
 *  Copyright (C) 2010 Zubanov Dmitry
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


/**
 *
 * @author Zubanov Dmitry aka javadimon, zubanov@gmail.com
 * Omsk, Russia, created 23.09.2010
 * (C) Copyright by Zubanov Dmitry
 */

package org.jssdb.core.filesystem;

import java.io.File;
import java.io.Serializable;
import java.text.MessageFormat;
import org.jssdb.core.DBProperties;
import org.jssdb.core.ram.RamHandler;

public class Transaction implements Serializable{
    
    private long id, lastModify;
    private Object object;
    private int transactionType = -1;
    public static int ADD = 0, MODIFY = 1, DELETE = 2;
    private static final long serialVersionUID = 344690125605722782L;

    public Transaction(long id, long lastModify, int transactionType, Object object){
        this.id = id;
        this.lastModify = lastModify;
        this.transactionType = transactionType;
        this.object = object;
    }

    public void makeTransaction(){
        if(object == null){
            return;
        }

        if(transactionType == ADD){
            String strF = DBProperties.getInstance().getPathToDB() +
                    object.getClass().getName() + File.separator + id;
            File f = new File(strF);
            if(f.isFile()){
                return;
            }

            RamHandler.getInstance().addObject(id, object);
            String strFile = DBProperties.getInstance().getPathToDB() +
                    object.getClass().getName() + File.separator + id;
            File file = new File(strFile);
            file.setLastModified(lastModify);
        }

        if(transactionType == MODIFY){
            RamHandler.getInstance().updateObject(id, object);
            String strFile = DBProperties.getInstance().getPathToDB() +
                    object.getClass().getName() + File.separator + id;
            File file = new File(strFile);
            file.setLastModified(lastModify);
        }

        if(transactionType == DELETE){
            RamHandler.getInstance().deleteObject(id, "" + object);
        }
    }

    @Override
    public String toString(){
        return MessageFormat.format("id = {0}, class name = {1}, "
                + "transaction type = {2}, ", new Object[]{id,
                object.getClass().getName(), transactionType});
    }

}
